package com.promote.sort;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName TwoSun
 * Description
 * @Author lizihao
 * Date 2021/3/17 10:04
 * @Version 1.0
 **/
public class TwoSum {
    public static void main(String[] args) {
        int[] numbers = new int[]{2,5,8,7,13};
        int target = 9;
        int[] ints = twoSum1(numbers, target);

        System.out.println("["+ints[0]+","+ints[1]+"]");
    }

        public static int[] twoSum(int[] numbers, int target) {
            if (numbers == null) return null;
            int i = 0; int j = numbers.length-1;
            while (i<j) {
                int sum = numbers[i] + numbers[j];
                if (sum == target) {
                    return new int[]{i+1,j+1};
                }else if (sum>target) {
                    j--;
                }else {
                    i++;
                }
            }
            return null;
        }


    public static int[] twoSum1(int[] nums, int target) {
        Map<Integer, Integer> m = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (m.get(target - nums[i]) != null) {
                return new int[]{m.get(target - nums[i]), i};
            }
            m.put(nums[i], i);
        }
        return new int[]{0, 0};
    }


}
